<?php
namespace app\login\controller;

use \think\Request;
use \think\Db;
use \think\Log;

class EmailCode
{
    public function index()
    {
    	$result = array('status' => 'success','msg'=>'请求成功');

    	$email = Request::instance()->param('email');

    	if(!isset($email)){
    		$result['status'] = 'error';
    		$result['msg'] = '未提供email';
    		return json($result);
    	}

    	if(!$this->isItelEmail($email)){
    		$result['status'] = 'error';
    		$result['msg'] = '请提供itel部门的email';
    		return json($result);
    	}

    	vendor('topthink.think-helper.src.Str');
    	$randNum = \think\helper\Str::randomNumber(6);
    	// $now =  \think\helper\Time::getMillisecond();
    	$now = date("Y-m-d H:i:s");
    	// 将email和验证码插入到数据库中
    	$sql = "INSERT INTO valcode (email,code,gentime,isused) VALUES ('$email','$randNum','$now',0)";
		$sql_exe_result = Db::execute($sql);
		if(!$sql_exe_result){	//插入到数据库失败
			$result['status'] = 'error';
    		$result['msg'] = '服务器繁忙中，请稍后再试';
    		return json($result);
		}
    	
    	//TODO 测试
    	$email = "913223548@qq.com";
    	$mail_result = think_send_mail($email,null,"吃饭 验证码","【吃饭】您的验证码是：".$randNum."。感谢您的使用。");

    	if($mail_result){
    		$result['status'] = 'success';
    		$result['msg'] = '验证码已发送，请注意查收';
    		return json($result);
    	}else{
    		$result['status'] = 'error';
    		$result['msg'] = '邮件服务器繁忙中，请稍后再试';
    		return json($result);
    	}
    }

    /**
    *   验证邮箱和验证码是否匹配
    */
    public function valide(){
        $result = array('status' => 'success','msg'=>'请求成功');

        $email = Request::instance()->param('email');
        $code = Request::instance()->param('code');

        if(!isset($email)){
            $result['status'] = 'error';
            $result['msg'] = '未提供email';
            return json($result);
        }

        if(!$this->isItelEmail($email)){
            $result['status'] = 'error';
            $result['msg'] = '请提供itel部门的email';
            return json($result);
        }

        if(!isset($code) || !$this->isCorrectCode($code)){
            $result['status'] = 'error';
            $result['msg'] = '未提供验证码或者验证码不正确';
            return json($result);
        }

        $srcsql = "SELECT IF(code=%d,true,false) result,gentime FROM valcode WHERE email='%s' ORDER BY gentime DESC LIMIT 1;";
        $sql = sprintf($srcsql,$code,$email);
        Log::info("EmailCode|valide==>   ".$sql);
        $sql_result = Db::query($sql);

        // var_dump($result);

        if(count($sql_result) == 0){   //没有查到数据
            $result['status'] = 'error';
            $result['msg'] = '登录失败';
            return json($result);
        }else if($this->isOutExpire($sql_result[0]['gentime'])){         //在超出了有效期
            $result['status'] = 'error';
            $result['msg'] = '登录失败,验证码已过期';
            return json($result);
        }


        $result['status'] = 'success';
        $result['msg'] = '登录成功';

        vendor('topthink.think-helper.src.Str');
        $token = \think\helper\Str::random(35);

        $userQuerySql = sprintf("SELECT Id FROM user WHERE email='%s' LIMIT 1;",$email);
        $user_cursor = Db::query($userSql);
        if(count($user_cursor) == 0){   //用户第一次请求登录，先走注册流程
            $userInsertSql = "INSERT INTO user(email,register_time) VALUES (":email",now());";
            $affect = Db::execute($userInsertSql,['email'=>$email]);

        }else{  //已经注册了，走登录

        }

        return json($result);
        
    }

    /**
    *   是否超出了有效期5分钟
    */
    private function isOutExpire($datetimeStr){
        $ExpireTime = strtotime("+5 minutes",strtotime($datetimeStr));
        $nowTime = time(); 
        // echo $datetimeStr."<=||=>".$ExpireTime."<=|=>".$nowTime;
        if($nowTime < $ExpireTime){  //在有效期
            return false;
        }else{
            return true;  
        }
    }


    /**
    *  是itel邮箱
    */
    private function isItelEmail($email){
		$regx = "/^\w[-\w.+]*@itel-mobile.com$/";
		return preg_match($regx,$email);
	}


    /**
    * 6位数的验证码
    */
    private function isCorrectCode($code){
        $regx = "/^\d{6}$/";
        return preg_match($regx,$code);
    }
}